﻿<?php
defined('IN_DESTOON') or exit('Access Denied');
require MD_ROOT.'/sell.class.php';
$do = new sell($moduleid);
$menus = array (
    array('添加'.$MOD['name'], '?moduleid='.$moduleid.'&action=add'),
    array($MOD['name'].'列表', '?moduleid='.$moduleid),
    array('审核'.$MOD['name'], '?moduleid='.$moduleid.'&action=check'),
    array('过期'.$MOD['name'], '?moduleid='.$moduleid.'&action=expire'),
    array('未通过'.$MOD['name'], '?moduleid='.$moduleid.'&action=reject'),
    array('回收站', '?moduleid='.$moduleid.'&action=recycle'),
    array('移动分类', '?moduleid='.$moduleid.'&action=move'),
    array('数据导入导出', '?moduleid='.$moduleid.'&action=inout'),
);

if(in_array($action, array('add', 'edit'))) {
	$FD = cache_read('fields-'.substr($table, strlen($DT_PRE)).'.php');
	if($FD) require DT_ROOT.'/include/fields.func.php';
	isset($post_fields) or $post_fields = array();
	$CP = $MOD['cat_property'];
	if($CP) require DT_ROOT.'/include/property.func.php';
	isset($post_ppt) or $post_ppt = array();
}
if(in_array($action, array('inout'))){
	
	$insertfields="itemid,catid,applyid,typeid,areaid,level,title ,introduce,model,standard,brand,unit,price,minamount,amount,days,tag,keyword,hits,thumb,thumb1,thumb2,username,groupid,company,vip,validated,truename,telephone,mobile,address, email,msn,qq, ali, skype,totime, editor, edittime, editdate, addtime, adddate, ip, template, status, linkurl, jiaoged, dengji, jiaoyi, biaom, cz, factory";
	$insertsql="INSERT INTO dt_sell (".$insertfields.") ";
	
	$selltl=array('项目ID','分类ID','应用ID','类型ID','地区ID','级别','标题','产品详细说明','产品型号','产品规格','产品品牌','单位','单价','最少起订量','总量', '发货期限', '标签', '关键字', '点击量', '图片路径1', '图片路径2', '图片路径3', '会员名', '会员组', '公司名', 'VIP', '审核时间', '姓名', '电话', '手机', '地址', 'EMAIL', 'MSN', 'QQ', '阿里旺旺', 'Skype', '过期时间', '添加人', '修改时间', '修改日期', '添加时间', '添加日期', 'IP', '模板', '状态', '链接',  '交割地', '产品等级', '交易方式', '表面处理', '材质', '生产厂家');
	
}
if($_catids || $_areaids) require DT_ROOT.'/admin/admin_check.inc.php';

if(in_array($action, array('', 'check', 'expire', 'reject', 'recycle'))) {
	$sfields = array('模糊', '产品名', '产品型号', '产品规格', '产品品牌', '计量单位', '标题', '简介', '公司名', '联系人', '联系电话', '联系地址', '电子邮件', '联系MSN', '联系QQ', '会员名', 'IP');
	$dfields = array('keyword', 'tag', 'model', 'standard', 'brand', 'unit', 'title', 'introduce', 'company', 'truename', 'telephone', 'address', 'email', 'msn', 'qq','username', 'ip');
	$sorder  = array('结果排序方式', '更新时间降序', '更新时间升序', '添加时间降序', '添加时间升序', VIP.'级别降序', VIP.'级别升序', '产品单价降序', '产品单价升序', '供货总量降序', '供货总量升序', '最小起订降序', '最小起订升序', '浏览次数降序', '浏览次数升序', '信息ID降序', '信息ID升序');
	$dorder  = array($MOD['order'], 'edittime DESC', 'edittime ASC', 'addtime DESC', 'addtime ASC', 'vip DESC', 'vip ASC', 'price DESC', 'price ASC', 'amount DESC', 'amount ASC', 'minamount DESC', 'minamount ASC', 'hits DESC', 'hits ASC', 'itemid DESC', 'itemid ASC');

	$level = isset($level) ? intval($level) : 0;
	$typeid = isset($typeid) ? ($typeid === '' ? -1 : intval($typeid)) : -1;
	isset($fields) && isset($dfields[$fields]) or $fields = 0;
	isset($order) && isset($dorder[$order]) or $order = 0;
	$thumb = isset($thumb) ? intval($thumb) : 0;
	$guest = isset($guest) ? intval($guest) : 0;
	$elite = isset($elite) ? intval($elite) : 0;
	$vip = isset($vip) ? intval($vip) : 0;
	$price = isset($price) ? intval($price) : 0;

	isset($datetype) && in_array($datetype, array('edittime', 'addtime', 'totime')) or $datetype = 'edittime';
	$fromdate = isset($fromdate) && preg_match("/^([0-9]{8})$/", $fromdate) ? $fromdate : '';
	$fromtime = $fromdate ? strtotime($fromdate.' 0:0:0') : 0;
	$todate = isset($todate) && preg_match("/^([0-9]{8})$/", $todate) ? $todate : '';
	$totime = $todate ? strtotime($todate.' 23:59:59') : 0;
	
	$minprice = isset($minprice) ? dround($minprice) : '';
	$minprice or $minprice = '';
	$maxprice = isset($maxprice) ? dround($maxprice) : '';
	$maxprice or $maxprice = '';
	$minamount = isset($minamount) ? dround($minamount) : '';
	$minamount or $minamount = '';
	$maxamount = isset($maxamount) ? dround($maxamount) : '';
	$maxamount or $maxamount = '';
	$minminamount = isset($minminamount) ? dround($minminamount) : '';
	$minminamount or $minminamount = '';
	$maxminamount = isset($maxminamount) ? dround($maxminamount) : '';
	$maxminamount or $maxminamount = '';
	$minvip = isset($minvip) ? intval($minvip) : '';
	$minvip or $minvip = '';
	$maxvip = isset($maxvip) ? intval($maxvip) : '';
	$maxvip or $maxvip = '';
	$itemid or $itemid = '';

	$fields_select = dselect($sfields, 'fields', '', $fields);
	$type_select = dselect($TYPE, 'typeid', $MOD['name'].'类型', $typeid);
	$level_select = level_select('level', '级别', $level);
	$order_select  = dselect($sorder, 'order', '', $order);

	$condition = '';
	if($_childs) $condition .= " AND catid IN (".$_childs.")";//CATE
	if($_areaids) $condition .= " AND areaid IN (".$_areaids.")";//CITY
	if($keyword) $condition .= " AND $dfields[$fields] LIKE '%$keyword%'";
	if($catid) $condition .= ($CAT['child']) ? " AND catid IN (".$CAT['arrchildid'].")" : " AND catid=$catid";
	if($areaid) $condition .= ($ARE['child']) ? " AND areaid IN (".$ARE['arrchildid'].")" : " AND areaid=$areaid";

	if($typeid >=0) $condition .= " AND typeid=$typeid";
	if($level) $condition .= " AND level=$level";
	if($thumb) $condition .= " AND thumb!=''";
	if($guest) $condition .= " AND username=''";
	if($elite) $condition .= " AND elite>0";
	if($vip) $condition .= " AND vip>0";
	if($price) $condition .= " AND price>0";
	if($minprice)  $condition .= " AND price>=$minprice";
	if($maxprice)  $condition .= " AND price<=$maxprice";
	if($minamount)  $condition .= " AND amount>=$minamount";
	if($maxamount)  $condition .= " AND amount<=$maxamount";
	if($minminamount)  $condition .= " AND minamount>=$minminamount";
	if($maxminamount)  $condition .= " AND minamount<=$maxminamount";
	if($minvip)  $condition .= " AND vip>=$minvip";
	if($maxvip)  $condition .= " AND vip<=$maxvip";
	if($fromtime) $condition .= " AND `$datetype`>=$fromtime";
	if($totime) $condition .= " AND `$datetype`<=$totime";
	if($itemid) $condition = " AND itemid=$itemid";

	$timetype = strpos($dorder[$order], 'add') !== false ? 'add' : '';
}
switch($action) {
	case 'add':
		if($submit) {
			if($do->pass($post)) {
				if($FD) fields_check($post_fields);
				if($CP) property_check($post_ppt);
				$do->add($post);
				if($FD) fields_update($post_fields, $table, $do->itemid);
				if($CP) property_update($post_ppt, $moduleid, $post['catid'], $do->itemid);
				dmsg('添加成功', '?moduleid='.$moduleid.'&action='.$action);
			} else {
				msg($do->errmsg);
			}
		} else {
			foreach($do->fields as $v) {
				isset($$v) or $$v = '';
			}
			$content = '';
			$status = 3;
			$addtime = timetodate($DT_TIME);
			$totime = '';
			$username = $_username;
			$typeid = 0;
			$item = array();
			$menuid = 0;
			$tname = $menus[$menuid][0];
			isset($url) or $url = '';
			if($url) {
				$tmp = fetch_url($url);
				if($tmp) extract($tmp);
			}
			include tpl('edit', $module);
		}
	break;
	case 'edit':
		$itemid or msg();
		$do->itemid = $itemid;
		if($submit) {
			if($do->pass($post)) {
				if($FD) fields_check($post_fields);
				if($CP) property_check($post_ppt);
				$do->edit($post);
				if($FD) fields_update($post_fields, $table, $do->itemid);
				if($CP) property_update($post_ppt, $moduleid, $post['catid'], $do->itemid);
				dmsg('修改成功', $forward);
			} else {
				msg($do->errmsg);
			}
		} else {
			$item = $do->get_one();
			extract($item);
			$addtime = timetodate($addtime);
			$totime = $totime ? timetodate($totime, 3) : '';
			$menuon = array('5', '4', '2', '1', '3');
			$menuid = $menuon[$status];
			$tname = '修改'.$MOD['name'];
			include tpl($action, $module);
		}
	break;
	case 'move':
		if($submit) {
			$fromids or msg('请填写来源ID');
			if($tocatid) {
				$db->query("UPDATE {$table} SET catid=$tocatid WHERE `{$fromtype}` IN ($fromids)");
				dmsg('移动成功', $forward);
			} else {
				msg('请选择目标分类');
			}
		} else {
			$itemid = $itemid ? implode(',', $itemid) : '';
			$menuid = 6;
			include tpl($action, $module);
		}
	break;
	case 'insert':
		if($submit) {
//$areaid or msg('请填写来源ID');
			if($fname = $_FILES['MyFile']['name']){
			$do = copy($_FILES['MyFile']['tmp_name'],$fname);     
			if ($do)      
			{      
				//echo "导入数据成功<br>";      
			} else {     
				//echo "";      
			}    
			}
			if(!empty($_SERVER["HTTP_CLIENT_IP"])){
  $cip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
  $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif(!empty($_SERVER["REMOTE_ADDR"])){
  $cip = $_SERVER["REMOTE_ADDR"];
}
else{
  die("ERROR. Could not get the IP adderss!");
}

//查询供应产品的最大ID
$sqlmaxid='SELECT max(itemid) FROM dt_sell';
$maxitemid = $db->query($sqlmaxid);
while ($r = mysql_fetch_array($maxitemid)) {
	$maxid = $r[0];

}

require_once 'template/Excel/reader.php';
// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader(); 
// Set output Encoding. 
$data->setOutputEncoding('utf-8');

//error_reporting(0);     
//导入CSV格式的文件     

error_reporting(E_ALL ^ E_NOTICE); 

$fname = $_FILES['MyFile']['name']; 

//”data.xls”是指要导入到mysql中的excel文件
$data->read($fname);
 
$mydate = date("Y-m-d");

for ($i = 4; $i <= $data->sheets[0]['numRows']; $i++) {

//以下注释的for循环打印excel表数据
/*
for ($j = 1; $j < = $data->sheets[0]['numCols']; $j++) {
echo """.$data->sheets[0]['cells'][$i][$j]."",";
}
echo "n";
*/
//以下代码是将excel表数据【3个字段】插入到mysql中，
//根据你的excel表字段的多少，改写以下代码吧！

$companyname=$data->sheets[0]['cells'][$i][8];
//die($companyname);
$compname = $companyname;
$sqlrowss='SELECT * FROM dt_company a, dt_member b where a.userid = b.userid and a.company = "'.$companyname.'" and a.groupid >"1"';
$resrowss = $db->query($sqlrowss);
print_r($resrowss['company']);

while ($r = mysql_fetch_array($resrowss)) {
	$ivip = $r['vip'];
	$ivalidated = $r['validated'];
	$itruename = $r['truename'];
	$itelephone = $r['telephone'];
	$imobile = $r['mobile'];
	$iaddress = $r['address'];
	$iemail = $r['email'];
	$imsn = $r['msn'];
	$iqq = $r['qq'];
	$iali = $r['ali'];
	$iskype = $r['skype'];
	$iusername = $r['username'];
	$igroupid = $r['groupid'];
	echo '<br/>'.$ivip.'|'.$ivalidated.'|'.$itruename.'|'.$itelephone.'|'.$imobile.'|'.$iaddress.'|'.$iemail.'|'.$imsn.'|'.$iqq.'|'.$iali.'|'.$iskype.'<br/><br/>';
 }

$ititle=$data->sheets[0]['cells'][$i][1];
$icompanys=$data->sheets[0]['cells'][$i][8];
if(trim($ititle) != '' && trim($icompanys) != '' ){
$maxid = (int)$maxid + 1;
//die("$itruename");
			$sql = "insert into dt_sell (itemid,catid,typeid,areaid,title,introduce,model,standard,brand,unit,price,minamount,amount,days,keyword,username,groupid,company,vip,validated,truename,telephone,mobile,address,email,msn,qq,ali,skype,adddate,editor,ip,status,linkurl,note,jiaoget,jiaoged,cz,factory) VALUES('".$maxid."','".$_POST['catid']."','".$_POST['typeid']."','".$_POST['areaid']."','".$data->sheets[0]['cells'][$i][1]."','".$_POST['introduce']."','".$_POST['model']."','".$data->sheets[0]['cells'][$i][3]."','".$_POST['brand']."','".$_POST['unit']."','".$data->sheets[0]['cells'][$i][4]."','".$_POST['minamount']."','".$data->sheets[0]['cells'][$i][5]."','".$_POST['days']."','".$data->sheets[0]['cells'][$i][1]."','$iusername','$igroupid','".$data->sheets[0]['cells'][$i][8]."','$ivip','$ivalidated','$itruename','$itelephone','$imobile','$iaddress','$iemail','$imsn','$iqq','$iali','$iskype','$mydate','$_username','".$cip."','0','show.php?itemid=$maxid','".$_POST['note']."','".$data->sheets[0]['cells'][$i][9]."','".$data->sheets[0]['cells'][$i][10]."','test','".$data->sheets[0]['cells'][$i][7]."')";
//echo $sql.'<br/>';
$db->query($sql);
}
}
dmsg('批量导入成功', $forward);
		} else {
//行业分类数据
$sqlsel="SELECT * FROM dt_category WHERE moduleid = '5'";
$ressel = $db->query($sqlsel);
//会员信息数据
$sqlmb="SELECT * FROM dt_member";
$resmb = $db->query($sqlmb);
			$itemid = $itemid ? implode(',', $itemid) : '';
			$menuid = 7;
			include tpl($action, $module);


		}
	break;
	case 'inout':
		ob_clean(); //清除之前所有输出的内容，防止输出出现乱码
		require_once MD_ROOT.'/phpexcel/Classes/PHPExcel.php';
		require_once MD_ROOT.'/phpexcel/Classes/PHPExcel/IOFactory.php';
		require_once MD_ROOT.'/phpexcel/Classes/PHPExcel/Reader/Excel5.php';
		if($exportsbt){
			if($post['catid'] <= '0' || empty($post['catid'])) msg('请选择要导出的行业分类'); // 判断是否选择了行业分类
			if (PHP_SAPI == 'cli') msg('本功能只能运行在网页浏览器'); // 适用范围
			
			$catname = $db->get_one("SELECT * FROM dt_category WHERE catid = '" . $post['catid']. "'");//EXCEL文件名
			$result = $db->query("SELECT ".$insertfields." FROM {$table} WHERE catid = '" . $post['catid']. "' ORDER BY itemid");//EXCEL数据

			// 创建EXCEL项目
			$objPHPExcel = new PHPExcel();
			
			// 设置EXCEL文件属性
			$objPHPExcel->getProperties()->setCreator("中国紧固件之都")
										 ->setLastModifiedBy("中国紧固件之都")
										 ->setTitle("中国紧固件之都")
										 ->setSubject("中国紧固件之都")
										 ->setDescription("http://www.cjgjzd.com")
										 ->setKeywords("中国紧固件之都")
										 ->setCategory("中国紧固件之都");
			$exlrow=1; 
			//$sheetnum = 0;//实现不同SHEET
			// 设备SHEET的名称
			$objPHPExcel->getActiveSheet(0)->setTitle($catname['catname']);
			
			
			// 设备当前起用的SHEET
			$objPHPExcel->setActiveSheetIndex(0);
			
			// 设置供应EXCEL文件的第一行名称
			$gstr='A';
			foreach($selltl as $v){
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue($gstr.'1', $v);
				$gstr++;
			}
			while($row = mysql_fetch_row($result)){
			
				$exlrow++;
				//输入数据
				$gstrt='A';
				foreach($row as $k){
					$kout=$k;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($gstrt.$exlrow, $kout);
					$gstrt++;
				}
			}
			
			
			// 定向输出到客户端的网页浏览器(Excel5)
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
			header("Content-Type:application/force-download");
			header("Content-Type:application/vnd.ms-execl");  
			header("Content-Type:application/octet-stream");
			header("Content-Type:application/download");
			
			header('Content-Disposition: attachment;filename="'.$catname['catname'].'.xls"');
			header("Content-Transfer-Encoding:binary");
			
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
			$objWriter->save('php://output');
			
			exit;
		}
		if($insertsbt) {
			$file=$_FILES['efile']['name'] ;
			$filetempname = $_FILES['efile']['tmp_name'];
			$fileext = substr($file, strlen($file)-4);
			if($fileext != 'xlsx' && $fileext !='.xls') msg('格式不正确，请选择XLS,XLSX文件');
			
			//上传EXCEL文件数据
			
			$filePath = 'file/upload/exl/';
			$str = "";
			$maxid = $db->get_one("SELECT MAX(itemid) AS num FROM {$table}");
			$maxnum = $maxid['num'];

			$filename=explode(".",$file);//把上传的文件名以"."号为准做一个数组。
			$time=date("y-m-d-H-i-s");//去当前上传的时间
			$filename[0]=$time;//取文件名t替换
			$name=implode(".",$filename); //上传后的文件名
			$uploadfile=$filePath.$name;//上传后的文件名地址
			
			//move_uploaded_file() 函数将上传的文件移动到新位置。若成功，则返回 true，否则返回 false。
			$resultt=move_uploaded_file($filetempname,$uploadfile);//假如上传到当前目录下
			
			if($resultt) //如果上传文件成功，就执行导入excel操作
			{
				$objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
				$objPHPExcel = $objReader->load($uploadfile);
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow(); // 取得总行数
				$highestColumn = $sheet->getHighestColumn(); // 取得总列数
				if($highestColumn!=''){
					$highestn=0;
					$en = 'A';
					while($highestColumn != $en){
						$highestn++;
						$en++;
					}
				}
			//循环读取excel文件,读取一条,插入一条
				for($j=2;$j<=$highestRow;$j++)
				{
					$en = 'B';
					$maxnum++;
					$strs[0]=$maxnum;
					for($k=2;$k<=$highestn+1;$k++)
					{
						$strs[$k-1] = $objPHPExcel->getActiveSheet()->getCell("$en$j")->getValue();//读取单元格
						if($k == 46){
							$strsarr = explode("=",$strs[$k-1]);
							$strs[$k-1] = $strsarr[0].'='.$maxnum;
						}
						$en++;
					}
					//explode:函数把字符串分割为数组。
					//$strs = explode("\\",$str);
					//print_r($str);
					$sqls = $insertsql." VALUES(";
					foreach($strs as $v){
						$sqls =$sqls."'".$v."',";
					}
					$sqls = substr($sqls,0,strlen($sqls)-1);
					$sqls .= ")";
					
					//mysql_query("SET NAMES UTF8"); //这就是指定数据库字符集，一般放在连接数据库后面就系了
					if(!$db->query($sqls))
					{die($k.'-'.$sqls);
					return false;
					}
					$str = "";
				}
				unlink($uploadfile); //删除上传的excel文件
				dmsg('导入EXCEL成功', $forward);
			}
			else
			{
				msg('导入EXCEL失败');
			}
		} else {
			$itemid = $itemid ? implode(',', $itemid) : '';
			$menuid = 8;
			include tpl($action, $module);
		}
	break;
	case 'update':
		is_array($itemid) or msg('请选择'.$MOD['name']);
		foreach($itemid as $v) {
			$do->update($v);
		}
		dmsg('更新成功', $forward);
	break;
	case 'tohtml':
		is_array($itemid) or msg('请选择'.$MOD['name']);
		foreach($itemid as $itemid) {
			tohtml('show', $module);
		}
		dmsg('更新成功', $forward);
	break;
	case 'delete':
		$itemid or msg('请选择'.$MOD['name']);
		isset($recycle) ? $do->recycle($itemid) : $do->delete($itemid);
		dmsg('删除成功', $forward);
	break;
	case 'restore':
		$itemid or msg('请选择'.$MOD['name']);
		$do->restore($itemid);
		dmsg('还原成功', $forward);
	break;
	case 'refresh':
		$itemid or msg('请选择'.$MOD['name']);
		$do->refresh($itemid);
		dmsg('刷新成功', $forward);
	break;
	case 'listorder':
		//print_r($_POST);exit;
		$do->listorder($listorders);
		dmsg('更新排序成功', $forward);
	break;
	case 'clear':
		$do->clear();
		dmsg('清空成功', $forward);
	break;
	case 'level':
		$itemid or msg('请选择'.$MOD['name']);
		$level = intval($level);
		$do->level($itemid, $level);
		dmsg('级别设置成功', $forward);
	break;
	case 'type':
		$itemid or msg('请选择'.$MOD['name']);
		$tid = intval($tid);
		array_key_exists($tid, $TYPE) or $tid = 0;
		$do->type($itemid, $tid);
		dmsg('类型设置成功', $forward);
	break;
	case 'recycle':
		$lists = $do->get_list('status=0'.$condition, $dorder[$order]);
		$menuid = 5;
		include tpl('index', $module);
	break;
	case 'reject':
		if($itemid && !$psize) {
			$do->reject($itemid);
			dmsg('拒绝成功', $forward);
		} else {
			$lists = $do->get_list('status=1'.$condition, $dorder[$order]);
			$menuid = 4;
			include tpl('index', $module);
		}
	break;
	case 'expire':
		if(isset($refresh)) {
			if(isset($extend)) {
				$days = isset($days) ? intval($days) : 0;
				$days or msg('请填写天数');
				$itemid or msg('请选择信息');
				foreach($itemid as $v) {
					$db->query("UPDATE {$table} SET totime=totime+$days*86400,status=3 WHERE itemid='$v' AND totime>0");
				}
				$do->expire();
				dmsg('延时成功', $forward);
			} else {
				$do->expire();
				dmsg('刷新成功', $forward);
			}
		} else {
			$lists = $do->get_list('status=4'.$condition);
			$menuid = 3;
			include tpl('index', $module);
		}
	break;
	case 'check':
		if($itemid && !$psize) {
			$do->check($itemid);
			dmsg('审核成功', $forward);
		} else {
			$lists = $do->get_list('status=2'.$condition, $dorder[$order]);
			$menuid = 2;
			include tpl('index', $module);
		}
	break;
	default:
		$lists = $do->get_list('status=3'.$condition, $dorder[$order]);
		$menuid = 1;
		include tpl('index', $module);
	break;
}
?>